<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/16 12:39
 */

namespace App\Project;

/**
 * 转换数组元素
 * Class Transform
 * @package App\Project
 */
class Transform
{
    protected $array = [];

    /**
     * @param $array
     * @return $this
     */
    public function setArray($array)
    {
        $this->array = $array;

        return $this;
    }

    public function get()
    {
        return $this->array;
    }

    public function convertArrayToJson(array $keys)
    {
        return $this->convert($keys, function ($value) {
            if (is_array($value)) {
                if (empty($value)) {
                    return null;
                }

                return json_encode($value, JSON_UNESCAPED_UNICODE);
            }

            return $value;
        });
    }

    public function convertArrayToString(array $keys, $glue = ',')
    {
        return $this->convert($keys, function ($value) use ($glue) {

            return implode($glue, (array)$value);
        });
    }

    public function convert($keys, $callback)
    {
        foreach ($keys as $key) {
            if (array_key_exists($key, $this->array)) {
                $this->array[$key] = $callback($this->array[$key]);
            }
        }

        return $this;
    }

}